from flask import (Blueprint,
                   render_template,
                   request,
                   redirect,
                   url_for,
                   session,
                   flash
                   )

from exts import db
from models import AdminModel, BorrowerModel
from createData import Create_data
from .forms import RegisterForm, LoginForm

bp = Blueprint("user", __name__, url_prefix="/")


# @bp.route("/a")
# def a():
#     # db.drop_all()
#     Create_data()
#     return "操作成功"


@bp.route("logout")#退出登录功能
def logout():
    #清楚session的所有数据
    session.clear()
    return redirect(url_for("base.index"))

@bp.route("/login", methods=["GET", "POST"])
def login():

    if request.method == "POST":
        form = LoginForm(request.form)
        if form.validate():
            username = form.name.data
            password = form.password.data
            level = form.level.data
            if level == '学生':
                user = BorrowerModel.query.filter_by(name=username).first()
                if user and user.password == password:
                    session['user_id'] = username
                    session['user_level'] = level
                    return redirect(url_for("base.index"))  # 学生存在且密码正确跳转学生界面
                else:
                    flash("用户不存在或密码错误！")
                    return redirect(url_for("user.login"))  # 学生不存在或密码错误返回
            else:
                user = AdminModel.query.filter_by(name=username).first()
                if user and user.password == password:
                    session['user_id'] = username
                    session['user_level'] = level
                    return redirect(url_for("base.index"))  # 管理员存在且密码正确跳转管理员界面
                else:
                    flash("用户不存在或密码错误！")
                    return redirect(url_for("user.login"))  # 管理员不存在或密码错误返回
        else:
            flash("用户名或密码格式错误！")
            return redirect(url_for("user.login"))  # 表单检验失败返回
    else:
        return render_template("login.html")  # get请求返回


@bp.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        form = RegisterForm(request.form)
        if form.validate():
            username = form.name.data
            password = form.password.data
            user = BorrowerModel(name=username, password=password)
            db.session.add(user)
            db.session.commit()#将新用户信息提交数据库
            return redirect(url_for("user.login"))#注册成功，跳转登录页面
        else:
            return redirect(url_for("user.register"))
    else:
        return render_template("register.html")#如果为GET请求，返回注册页面
